<!--
 * @Description: 花了还有无感结算页面
 * @Author: Kerwin
 * @Date: 2025-05-26 14:46:49
 * @LastEditTime: 2025-11-25 09:56:01
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="physicalShopCheck">
    <u-navbar
      :title-bold="false"
      v-if="!isWeChatBrowser"
      :is-back="false"
      color="#333"
      :background="{ backgroundColor: '#f9c9ae' }"
    >
      <template #right>
        <view style="margin: 0 20rpx" @click="clearUser">
          <u-icon name="man-delete" color="#999999" size="42"></u-icon>
        </view>
      </template>
    </u-navbar>
    <!-- 头部 -->
    <view class="topTitLe">
      <view class="leftTitle">
        <view style="font-weight: 700; font-size: 32rpx; margin-bottom: 20rpx"
          >消费总金额</view
        >
        <view style="color: #999">请询问金额后提交</view>
      </view>
      <view class="rightTitle">
        <u-image width="180rpx" height="150rpx" :src="moneyIcon"></u-image>
      </view>
    </view>
    <!-- 商户信息 -->
    <view class="shopBox">
      <text class="name"
        ><u-icon
          size="40"
          style="vertical-align: middle"
          :name="shopIcon1"
        ></u-icon>
        {{ info.name }}</text
      >
      <view class="inptBox">
        <u-input
          v-model="money"
          v-input-decimal2
          type="digit"
          inputmode="decimal"
          focus
          pattern="number"
          placeholder="¥ 0.00"
          input-align="center"
          :custom-style="{
            fontSize: '52rpx'
            // fontWeight: '800'
          }"
          :disabled="inptDisabled"
        />
        <text class="unit">(元)</text>
      </view>
      <view class="yt-list-cell shape2" v-if="isHjfShop">
        <view class="cell-tit">
          抵用券抵扣：<text class="red"
            >（本次最多使用{{ scoreMax }}积分，可抵扣{{ scoreMax }}元）</text
          ></view
        >
        <view class="cell-tip">
          <view class="wallet"> 抵用券剩余：{{ userScore }}</view>
          <!-- <u-number-box :disabled="!userScore" v-model="score_consumption" :max="scoreMax" :min="0"></u-number-box> -->
          <view class="right" style="width: 250rpx">
            <u-input
              class="inputBox"
              :disabled="!userScore && userScore < 0"
              v-input-decimal
              placeholder="请输入抵扣积分"
              type="digit"
              v-model="score_consumption"
              @blur="onScoreChange"
              :border="true"
            />
          </view>
        </view>
        <view class="hjfScore"> 绿色积分剩余：{{ hjfUserScor }}</view>
      </view>

      <view
        class="radioBox"
        v-if="info.shopMoneyRules && info.shopMoneyRules.length > 1"
      >
        <u-radio-group
          v-model="moneyRuleId"
          @change="radioGroupChange"
          :wrap="true"
        >
          <u-radio
            v-for="(item, index) in info.shopMoneyRules"
            :key="index"
            :name="item.moneyRuleId"
          >
            {{ item.userMoneyRuleName }}
          </u-radio>
        </u-radio-group>
      </view>
      <!-- <u-form-item label-width="auto" label-position="top" :border-bottom="false" label="付款留言：">
        <u-input style="background-color: #f7f5f5; " :height="200" :border="true" type="textarea"
          v-model="orderData.remark" />
      </u-form-item> -->
    </view>
    <!-- 结算 -->
    <u-button
      :disabled="!info.shopId"
      class="hy-btn"
      type="primary"
      ripple
      @click="toPayment"
    >
      确认付款
    </u-button>
    <view class="hy-link" v-if="bindPhone" @click="toBindPhone">
      绑定手机号
    </view>

    <!-- #ifdef H5 -->
    <!-- <hyDownloadTips /> -->
    <!-- #endif -->
  </view>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { onLoad, onShow, onLaunch } from '@dcloudio/uni-app'
//存储
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore } from '@/store'
//api
import { enumAll, moneyApi, orderApi, productApi, userApi } from '@/api'
//  组件
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
//工具
import {
  getQueryVariable,
  parseParams,
  getQueryObject,
  isWeChat
} from '@/utils/common'
import debounce from 'lodash/debounce'
//图片
import moneyIcon from '@/static/hlhy/money2.png'
import shopIcon1 from '@/static/hlhy/shopIcon1.png'

//初始数据
const configStore = useConfigStore()
const userStore = useUserStore()
const { enterByStoreQrcode, isWeChatBrowser, isAlipayClient } =
  storeToRefs(configStore)
const { accessToken, useShareCode } = storeToRefs(userStore)
const info = reactive<any>({
  name: '',
  shopId: '',
  shopMoneyRules: []
})
const money = ref()
const orderData = ref<any>({
  remark: ''
})
const productSku = ref()
const flqScore = ref()
const moneyRuleId = ref(null)
const userInfo = userStore.userInfo
const userPhone = ref('')
const bindPhone = ref(false) //绑定手机号状态
const login_success = ref({})
// 创建订单
async function creatOrder() {
  console.log('提交的订单信息', orderData.value)
  try {
    const { data } = await orderApi.orderAdd(orderData.value)
    console.log('订单创建成功==>', data)
    if (data) {
      console.log(
        '跳转==>',
        `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
      )
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    }
  } catch (err) {
    console.log(err)
  }
  uni.hideLoading()
}

const onScoreChange = (e: number) => {
  e = Number(e)
  console.log(e, 'x')
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请先输入支付金额'
    })
    score_consumption.value = 0
    return
  }
  if (e < 0) {
    uni.showToast({
      icon: 'none',
      title: '积分有误'
    })
    score_consumption.value = scoreMax.value
    userScore.value = Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    console.log(111)
  } else if (e <= scoreMax.value) {
    console.log(222)

    score_consumption.value = e
    userScore.value = Math.floor((maxUserScor.value - e) * 10) / 10
  } else {
    console.log(333)

    score_consumption.value = scoreMax.value
    userScore.value = Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    uni.showToast({
      icon: 'none',
      title: '积分有误'
    })
  }
}
// 创建防抖版本的 creatOrder 函数，500 毫秒内只执行一次
const debouncedCreatOrder = debounce(creatOrder, 500)

async function toPayment() {
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请输入支付金额'
    })
    return
  }
  if (money.value <= 0) {
    uni.showToast({
      icon: 'none',
      title: '最低金额需大于0元'
    })
    return
  }
  if (score_consumption.value > scoreMax.value) {
    uni.showToast({
      icon: 'none',
      title: '最多只能抵扣' + scoreMax.value + '元'
    })
    return
  }

  uni.showLoading({ title: '', mask: true })
  try {
    await getShopSku()
    // 卖手推荐的门店，卖手获得收益
    // 2023/9/11 扫店铺付款码进入无shareCode则不携带
    if (uni.getStorageSync('shareCode') && useShareCode.value) {
      orderData.value.orderProductSkus[0].externalData = {
        userShareCode: uni.getStorageSync('shareCode')
      }
    }
    // 调用防抖函数
    debouncedCreatOrder()
  } catch (err) {
    uni.hideLoading()
  }
}

//获取商铺sku
const getShopSku = async () => {
  const { data } = await productApi.getShopProductSkuList({
    detail: false,
    dynamicPrice: true,
    shopId: info.shopId
  })
  if (data.records) {
    productSku.value = data.records[0]
    orderData.value.orderProductSkus = [
      {
        count: 1,
        money: money.value,
        shopProductSkuId: productSku.value.id,
        moneyRuleId: moneyRuleId.value,
        dynamicPric: true
      }
    ]
    if (score_consumption.value) {
      orderData.value.scoreMoney = score_consumption.value
    }
  }
}

//获取用户信息
const getUserDetailInfo = async () => {
  const { data } = await userApi.userInfo()
  console.log('用户数据', data)

  if (data && data.phone) {
    userPhone.value = data.phone
  } else {
    userPhone.value = ''
  }
}

// // 是否显示绑定手机号
// function updateBindPhoneStatus(login_success: any) {
//   if (login_success.status) {
//     getUserDetailInfo(); // 会自动触发 watch 更新 bindPhone
//   }
// }

watch(
  userPhone,
  (newPhone) => {
    bindPhone.value = !newPhone || newPhone.trim() === ''
  },
  { immediate: true }
)

// 监听登录状态变化来更新 bindPhone 状态
watch(
  () => userStore.hasLogin,
  (newLoginStatus) => {
    if (newLoginStatus) {
      // 登录成功后检查手机号
      getUserDetailInfo()
    } else {
      // 未登录时默认需要绑定手机号
      bindPhone.value = true
    }
  },
  { immediate: true }
)

const isHjfShop = ref(false) // 是否花积分
const isflqShop = ref(false) // 是否复来券
const score_consumption = ref(0)
const userScore = ref(0) // 用户积分余额
const hjfUserScor = ref(0) //花积分的积余额
const maxUserScor = ref(0) //固定积分上限

let _userScore = 0
async function getScore(walletRuleId: any) {
  const { data } = await moneyApi.walletInfo({
    walletRuleId
  })
  if (walletRuleId == 2013) {
    console.log('积分', data)
    hjfUserScor.value = Math.floor(data.money * 100) / 100
  } else {
    userScore.value = Math.floor(data.money * 10) / 10
    maxUserScor.value = Math.floor(data.money * 10) / 10
    _userScore = Math.floor(data.money * 10) / 10
  }
}

//查询让利规则
const getRule = async () => {
  console.log(productSku.value, 5555)


const scoreMax = computed(() => {
  if (!orderData) return 0
  if (money.value) {
    let _money = 0
    if (isHjfShop.value) {
      _money = money.value / 2
    }

    if (_money > maxUserScor.value) {
      // score_consumption.value = Math.floor(userScore.value * 10) / 10
      return Math.floor(maxUserScor.value * 10) / 10
    } else {
      // score_consumption.value = Math.floor(_money * 10) / 10
      return Math.floor(_money * 10) / 10
    }
  } else {
    score_consumption.value = 0
    return 0
  }
})

async function getShopInfo() {
  const { data } = await productApi.getShopInfo({
    id: info.shopId,
    detail: true,
    otherColumns: 'moneyRuleDetails'
  })
  const { name, shopMoneyRules, code, user, integralsRuleId } = data
  uni.setStorageSync('shopCode', code)
  uni.setStorageSync('shopOwnerShareCode', user.shareCode)
  info.name = name
  //判断是否是花积分和复来券
  if (integralsRuleId == 1) {
    isHjfShop.value = true
    getScore(enumAll.wallet_rule_id_enum.花积分钱包)
    getScore(enumAll.wallet_rule_id_enum.绿色积分钱包)
  } else if (integralsRuleId == 4) {
    //复来券
    isflqShop.value = true
    await getShopSku()
    getScore(enumAll.wallet_rule_id_enum.复来券钱包)
    getRule()
  }
  if (shopMoneyRules && shopMoneyRules.length > 0) {
    if (moneyRuleId.value) {
      // 判断url携带的moneyRuleId是否还存在（可能规则已删除，但是码或者链接存在滞后）
      const rule = shopMoneyRules.find(
        (item: { moneyRuleId: null }) => item.moneyRuleId == moneyRuleId.value
      )
      if (!rule) {
        info.shopMoneyRules = shopMoneyRules
        moneyRuleId.value = shopMoneyRules[0].moneyRuleId
      }
    } else {
      info.shopMoneyRules = shopMoneyRules
      moneyRuleId.value = shopMoneyRules[0].moneyRuleId
    }
  }
}
watch(accessToken, (newValue, oldValue) => {
  getShopInfo()
})
watch(money, (newValue, oldValue) => {
  console.log(newValue, oldValue, '输入的金额')
  if (newValue) {
    nextTick(() => {
      money.value = newValue.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })
    if (newValue < 0) {
      uni.showToast({
        icon: 'none',
        title: '金额不能小于0'
      })
      money.value = 0
    } else {
      score_consumption.value = scoreMax.value
      userScore.value =
        Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    }
  } else {
    userScore.value = Math.floor(maxUserScor.value * 10) / 10
  }
})

//跳转到绑定手机号·
const toBindPhone = () => {
  //将当前url存在本地
  uni.setStorageSync('currentUrl', window.location.href)
  uni.navigateTo({
    url: '/pages/physicalShopCheck/bindPhone'
  })
}

function radioGroupChange(e: any) {
  console.log(e)
}

//清空用户信息
const clearUser = () => {
  userStore.syncClearToken()
  userStore.syncClearUserInfo()
  const tempParams = getQueryObject(window.location.search)
  uni.navigateTo({
    url: `/pages/physicalShopCheck/hlhyPay?&qrcode=${tempParams.qrcode}&shopId=${tempParams.shopId}&shareCode=${tempParams.shareCode}`
  })
}

const honbaoStatus = ref(false)
const inptDisabled = ref(false)
const btnColor = ref('2979ff')
const maxRetryCount = 3 // 设置最大重试次数
let retryCount = 0 // 当前重试次数

// 初始化逻辑

onLoad(async (option) => {
  retryCount = 0 // 重置重试次数
  // wxOptions.value = option;

  if (isWeChatBrowser.value) {
    honbaoStatus.value = true
    await handleAuth(option, handleWeChatAuth)
  } else {
    console.log('支付宝的', userStore.hasLogin)
    if (!userStore.hasLogin) {
      const tempParams = getQueryObject(window.location.search)
      uni.navigateTo({
        url: `/pages/login/index?&qrcode=${tempParams.qrcode}&shopId=${tempParams.shopId}&shareCode=${tempParams.shareCode}`
      })
    }
    getMes(option)
  }
})

// 获取店铺信息
function getMes(option: any) {
  if (!option) return

  const { shopId, moneyRuleId, money, color, deviceCode } = option
  info.shopId = shopId || ''
  info.deviceCode = deviceCode || ''
  moneyRuleId && (moneyRuleId.value = moneyRuleId)
  money && ((money.value = money), (inptDisabled.value = true))
  color && (btnColor.value = color)

  getShopInfo()
}

// 处理授权和登录逻辑
async function handleAuth(
  option: any,
  authMethod: (option: any) => Promise<void>
) {
  try {
    console.log('支付宝授权处理1', retryCount, option)

    await authMethod(option)
    // 授权成功后重置 retryCount
    retryCount = 0
  } catch (error) {
    handleAuthError(error, option, authMethod)
  }
}
// 处理支付宝授权和登录
async function handleAlipayAuth(option: any) {
  console.log('授权处理', retryCount)
  const user_id = await userStore.aliAuth()
  console.log('用户ID:', user_id)
  const openid = user_id

  const login_success: any = await userStore.hlhyLoginByOpenId(openid)
  console.log(login_success, '用户登录是否成功', option)

  if (!login_success.status) {
    throw new Error('登录失败')
  }

  console.log(userInfo, '用户信息')
  // updateBindPhoneStatus(login_success)

  // 只在登录成功时调用 getMes
  console.log('传递的optins--》', option)

  getMes(option)
}

// 处理微信授权和登录
async function handleWeChatAuth(option: any) {
  console.log('进入无感支付微信授权', option, 'xxxx')

  await userStore.wxAuth()

  const codeAuth = getQueryVariable('code')
  console.log('微信授权码', codeAuth)

  if (!codeAuth) {
    throw new Error('获取微信授权码失败')
  }

  await userStore.wxWebLogin(codeAuth) //获取openid
  const login_success: any = await userStore.hlhyLoginByOpenId()
  console.log('授权成功吗?===>', login_success)

  if (!login_success.status) {
    throw new Error('登录失败')
  }

  console.log(userInfo, '用户信息', login_success.status)
  getUserDetailInfo()

  // updateBindPhoneStatus(login_success)

  // if (!login_success.subscribe && login_success.subscribe != 1) {
  //   uni.showModal({
  //     title: '提示',
  //     "confirmText":'去关注',
  //     content: '您还未关注“鑫复来”公众号，\n只有关注之后才能领取红包！\n是否立即关注？',
  //     success: (res) => {
  //       if (res.confirm) {
  //         // uni.navigateTo({
  //         //   url: '/pages/webview/index?url=' + encodeURIComponent('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzkxNDYyOTc5Nw==&scene=110#wechat_redirect')
  //         // })
  //         window.location.href =
  //           'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzkxNDYyOTc5Nw==&scene=110#wechat_redirect​'

  //       }
  //     }
  //   })
  // }

  // 只在登录成功时调用
  console.log('传递的optins--》', option)
  getMes(option)
}

// 处理授权错误
// 处理授权错误（调整条件判断）
function handleAuthError(
  error: any,
  option: any,
  authMethod: (option: any) => Promise<void>
) {
  console.error('授权或登录失败:', error, userStore.hasLogin)

  let errorMessage = '授权或登录失败，请重试'
  if (error?.errorDesc) errorMessage = error.errorDesc

  uni.showToast({ title: errorMessage, icon: 'none' })

  // 主要调整：不依赖 userStore.hasLogin，直接根据重试次数判断
  console.log(retryCount, '失败次数')

  if (retryCount < maxRetryCount) {
    retryCount++
    uni.showModal({
      title: '授权失败',
      content: `剩余 ${maxRetryCount - retryCount} 次重试机会`,
      success: (res) => {
        if (res.confirm) handleAuth(option, authMethod)
      }
    })
  } else {
    uni.showToast({ title: '授权失败次数过多，请稍后重试', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.physicalShopCheck {
  padding: 30rpx;
  text-align: center;
  background: linear-gradient(#fab791 0%, rgba(255, 250, 224, 0) 30%);

  .topTitLe {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .leftTitle {
      text-align: left;
    }
  }

  .shopBox {
    // margin: 0 10rpx;
    min-height: 300rpx;
    padding: 20rpx;
    background: url('@/static/pay1.png') no-repeat;
    background-size: 100% 100%;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1); // 外部阴影

    .name {
      text-align: center;
      margin-top: 20rpx;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .inptBox {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding: 20rpx 0;
    border-top: 1px solid #8080802e;
    border-bottom: 1px solid #8080802e;
    position: relative;
    margin-top: 40rpx;
    font-size: 50rpx;

    .unit {
      right: 0;
      top: 36rpx;
      font-size: 28rpx;
      margin-bottom: 10rpx;
    }
  }

  .yt-list-cell {
    display: flex;
    align-items: center;
    padding: 40rpx 0;
    position: relative;

    .cell-tit {
      flex: 1;
      font-size: 26rpx;
      color: #909399;
      text-align: left;

      .red {
        // color: #f92c1d;
        color: #ff6c18;
      }
    }

    &.shape2 {
      display: block;

      .cell-tip {
        display: flex;
        justify-content: space-between;
        margin-top: 20rpx;
        align-items: center;

        .wallet {
          font-size: 28rpx;
          color: #ff6c18;
        }
      }
    }
  }
  .hjfScore {
    margin-top: 10rpx;
    text-align: left;
    color: #909399;
  }

  .radioBox {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;

    :deep(.u-radio) {
      justify-content: center;
    }
  }

  .hy-btn {
    margin-top: 50rpx;
  }
  .hy-link {
    margin-top: 30rpx;
    text-align: right;
    color: #909399;
    //下划线
    text-decoration: underline;
  }
}

.inputBox {
  // border: none;
  // border-top: 1rpx solid #e1e1e1;
  // border-bottom: 1rpx solid #e1e1e1;
}
</style>
